<template>
  <div :id="id"></div>
</template>

<script>
import wangEditor from 'wangeditor'
import request from 'utils/request'
// import db from "utils/localstorage";

export default {
  name: 'editor',
  props: {
    html: {
      type: String,
      default: ''
    },
    height: {
      type: Number,
      default: 480
    },
    id: {
      type: String,
      default: Math.random().toString(36).substr(-8)
    }
  },
  data () {
    return {
      editor: null,
      editorData: this.html || ''
    }
  },
  watch: {
    html (val) {
      if (this.editor) {
        this.editor.txt.html(val)
      }
    }
  },
  mounted () {
    const editor = new wangEditor(`#${this.id}`)
    // 配置onchange回调函数，将数据同步到data中
    editor.config.showLinkImg = false
    editor.config.menus = [
      'head',
      'bold',
      'fontSize',
      'fontName',
      'italic',
      'underline',
      'strikeThrough',
      'indent',
      'lineHeight',
      'foreColor',
      'backColor',
      'link',
      'list',
      'justify',
      'quote',
      'image',
      'video',
      'table',
      'splitLine',
      'undo',
      'redo'
    ]
    editor.config.zIndex = 100
    editor.config.height = this.height
    // editor.config.uploadImgServer = 'https://mini.landlt.com/lantd-fish/oss_upload' // 上传图片的服务
    editor.config.uploadImgShowBase64 = true
    editor.config.uploadImgMaxLength = 1 // 限制一次最多上传 1 张图片
    // editor.config.uploadFileName = 'file'
    // editor.config.uploadImgHeaders = {
    //     Authentication: db.get('USER_TOKEN'),
    // }
    // 完全自定上传图片的配置项
    editor.config.customUploadImg = async function (resultFiles, insertImgFn) {
      const formData = new FormData();
      var timestamp = new Date().getTime();
      const file = resultFiles[0];
      const oldFileName = file.name;
      const newFileName = oldFileName.replace(".", timestamp + ".");
      const newFile = new File([file], newFileName)
      formData.append("file", newFile);
      formData.append('forceUpdate', '1');
      formData.append('path', 'm1/' + newFileName);
      let data = await request.upload('/oss_upload', formData);
      if (data.data.code == 200) {
        console.log(data.data.data.absPath)
        insertImgFn(data.data.data.absPath);
      }
    }
    // editor.config.uploadImgHooks = {
    //   customInsert: function(insertImgFn, result) {
    //       // result 即服务端返回的接口
    //       // insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
    //       insertImgFn(result.data.absPath)
    //   },
    // }
    editor.config.onchange = (newHtml) => {
       this.editorData = newHtml
       this.$emit('editorChange', newHtml)
    }

    // 创建编辑器
    editor.create()
    editor.txt.html(this.html)
    this.editor = editor
  },
  getEditorData () {
    return this.editor.txt.html()
  },
  beforeDestroy() {
    // 调用销毁 API 对当前编辑器实例进行销毁
    this.editor.destroy()
    this.editor = null
  }
}
</script>
